package com.yylending.las.lending.video;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.Loader;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.bairuitech.anychat.AnyChatDefine;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Constants;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.lending.quota.myquota.MyQuotaModel;
import com.yylending.las.lending.quota.myquota.MyQuotaPresenter;
import com.yylending.remotevideo.AnyChat;
import com.yylending.remotevideo.AnyChatPresenter;
import com.yylending.remotevideo.Global;
import com.yylending.remotevideo.RemoteVideoActivity;
import com.yylending.remotevideo.config.ScreenInfo;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by HenryZhang on 2017/4/11.<br>
 * Copyright © 2017 www.yylending.com. All Rights Reserved.<br><br>
 * <p>
 * 视频见证
 */
public class VideoVerifyActivity extends BaseActivity implements
		AnyChatPresenter.View, SignPresenter.View, MyQuotaPresenter.View, //VideoPresenter.View,
		View.OnClickListener {
	private static final String TAG = VideoVerifyActivity.class.getSimpleName();

	private static final int PERMISSION_REQUEST_CODE = 100;

	private static final int LOADER_ID_ANY_CHAT = 102;
	private static final int LOADER_ID_SIGN = 9101;
	private static final int LOADER_ID_MY_QUOTA = 9102;

	/**
	 * 申请连线
	 */
	private static final int STATUS_CONNECTION = 0;
	/**
	 * 连线成功，等待被呼叫
	 */
	private static final int STATUS_CANCEL = 1;
	/**
	 * 断线
	 */
	private static final int STATUS_RECONNECTION = 2;

	private AnyChatPresenter mAnyChatPresenter;
	private SignPresenter mSignPresenter;
	private MyQuotaPresenter mMyQuotaPresenter;

	@BindView(R.id.video_verify_connection_container)
	RelativeLayout mConnectionContainer;
	@BindView(R.id.video_verify_complete_container)
	RelativeLayout mVerifyCompleteContainer;
	@BindView(R.id.video_verify_loan_money_tv)
	TextView mLoanMoney;
	/**
	 * 状态：申请连接、等待视频呼叫
	 */
	@BindView(R.id.video_verify_wait_ic_iv)
	View mQueuePositionIcon;
	@BindView(R.id.video_verify_queue_front)
	TextView mQueuePosition;
	@BindView(R.id.video_verify_waiting_time)
	TextView mWaitingTime;
	@BindView(R.id.video_verify_connection_state)
	ImageView mConnectionState;
	@BindView(R.id.video_verify_action)
	Button mActionBtn;

	private int mStatus = STATUS_CONNECTION;

	private boolean mGrantedCamera = false;
	private boolean mGrantedMicrophone = false;

	private static final String mEXTRA_LOAN_AMOUNT = "extra_loan_amount";

	private String mLoanAmount = "0";

	public static void start(Activity aty, String loanAmount) {
		Intent i = new Intent(aty, VideoVerifyActivity.class);
		i.putExtra(mEXTRA_LOAN_AMOUNT, loanAmount);
		aty.startActivity(i);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_ANY_CHAT:
				return new PresenterLoader<>(this, new AnyChatPresenter.Generator());
			case LOADER_ID_SIGN:
				return new PresenterLoader<>(this, new SignPresenter.Generator());
			case LOADER_ID_MY_QUOTA:
				return new PresenterLoader<>(this, new MyQuotaPresenter.Generator());
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_ANY_CHAT:
				mAnyChatPresenter = (AnyChatPresenter) data;
				mAnyChatPresenter.attach(this);
				showLoading(true);
				mActionBtn.setEnabled(false);
				mAnyChatPresenter.initAnyChat(this);
				break;
			case LOADER_ID_SIGN:
				mSignPresenter = (SignPresenter) data;
				mSignPresenter.attach(this);
				break;
			case LOADER_ID_MY_QUOTA:
				mMyQuotaPresenter = (MyQuotaPresenter) data;
				mMyQuotaPresenter.attach(this);
				break;
		}
	}

	@Override
	public void onBackPressed() {
		exit();
	}

	@Override
	protected void onDestroy() {
		AnyChat.stopCallingSession(this);
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
		dismissLoading();
		getSupportLoaderManager().destroyLoader(LOADER_ID_ANY_CHAT);
		getSupportLoaderManager().destroyLoader(LOADER_ID_SIGN);
		getSupportLoaderManager().destroyLoader(LOADER_ID_MY_QUOTA);
		super.onDestroy();
	}

	/**
	 * 面签任务编号
	 */
	private String mNumber;
	private static final int TIME_UPDATE = 301;
	private Timer mTimer;
	private TimerTask mTimerTask;
	private Handler mTimeHandler;
	/**
	 * 每个人预计等待时间6分钟
	 */
	private int mCounter = 6;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//亦可在Layout某View里设置keepScreenOn=true（需要visible）
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_video_verify);
		ButterKnife.bind(this);
		setTitle(R.string.video_verify);

		Intent i = getIntent();
		if (i != null) {
			mLoanAmount = i.getStringExtra(mEXTRA_LOAN_AMOUNT);
		}

		mActionBtn.setOnClickListener(this);
		changeViewStatus(mStatus);
		//实时更新显示时间
		mTimeHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == TIME_UPDATE) {
					if (mStatus == STATUS_CANCEL) {
						// 计算等待时间
						int wait;
						if(mQueueCurrent == -1){
							wait = mCounter;
						}else{
							wait = mQueueCurrent * 6 + mCounter;
						}
						String time = getString(R.string.video_verify_need_wait, wait);
						CLog.d(TAG, "还需等待："+wait);
						mWaitingTime.setText(time);
						if (mCounter != 1){
							mCounter--;
						}
						if (mCounter == 0) {
							mCounter = 6;
						}
					} else {
						mWaitingTime.setText("");
					}
				}
			}
		};
		//设置屏幕信息
		DisplayMetrics dMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
		ScreenInfo.WIDTH = dMetrics.widthPixels;
		ScreenInfo.HEIGHT = dMetrics.heightPixels;

		getSupportLoaderManager().initLoader(LOADER_ID_ANY_CHAT, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_MY_QUOTA, null, this);
		applyPermission();
	}

	@Override
	protected void onStart() {
		super.onStart();
		com.yylending.las.Global.setThirdPartyPageOpenedFlag(false);
		if (mStatus == STATUS_CONNECTION)
			mSignPresenter.getSign();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void anyChatInitializeComplete() {
		getSupportLoaderManager().initLoader(LOADER_ID_SIGN, null, this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_back:
				exit();
				break;
			case R.id.video_verify_action:
//				RemoteVideoActivity.start(this, -1, -1);break;//for test because any chat server is fucking any time
				switch (mStatus) {
					case STATUS_CONNECTION:
						break;
					case STATUS_CANCEL:
						cancel();
						break;
					case STATUS_RECONNECTION:
						mAnyChatPresenter.reconnection();
						break;
				}
			default:
				super.onClick(v);
				break;
		}
	}

	private void exit() {
		showLoading(false);//loading不可取消，防止重复点击返回按钮
		if (mStatus == STATUS_CANCEL) {
			StatService.onEvent(this, StatIDSet.EVENT_ID_CANCEL_THE_LINE);
			cancel();
		} else {
			if (mAnyChatPresenter != null) {
				mAnyChatPresenter.releaseAnyChat();
			}
			onBackBtnPressed();
		}
	}

	private void applyPermission() {
		dismissLoading();
		if (PermissionsGrantedHelper.isSdkUnderM()) {
			if (PermissionsGrantedHelper.checkCameraPermission()) {
				CLog.i(TAG, "相机权限已打开");
				mGrantedCamera = true;
			} else {
				mGrantedCamera = false;
				showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
			}
		} else {
			PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.CAMERA);//摄像头权限
		}
		PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.RECORD_AUDIO);//麦克风权限
	}

	private void cancel() {
		if (isFinishing())
			return;//isDestroyed() api 17
		showTwoBtnDialogWithLeftTextColor("",
				getString(R.string.dequeue_alert_text), getString(R.string.dequeue_cancel), getString(R.string.dequeue_confirm),
				new CommonDialog.ButtonClickListener() {
					@Override
					public void onConfirm(CommonDialog dialog) {
						dialog.dismiss();
					}

					@Override
					public void onCancel(CommonDialog dialog) {
						mAnyChatPresenter.quitQueue();
						mAnyChatPresenter.releaseAnyChat();
						finish();
						dialog.dismiss();
					}
				}, true, R.color.color_999999);
	}

	@Override
	public void progressDialogCancel(DialogInterface dialog) {
//		finish();
	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.CAMERA:
					if (permission.granted) {
						mGrantedCamera = true;
					} else {
						showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
					}
					break;
				case Manifest.permission.RECORD_AUDIO:
					if (permission.granted) {
						mGrantedMicrophone = true;
					} else {
						showNeedPermission(getString(R.string.mic_permission_hint, getString(R.string.app_name)));
					}
					break;
				default:
					break;
			}
		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {
		}
	};

	private void showNeedPermission(String tips){
		showTwoBtnDialog(tips, getString(R.string.go_to_settings), getString(R.string.cancel), new CommonDialog.ButtonClickListener() {
			@Override
			public void onCancel(CommonDialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirm(CommonDialog dialog) {
				//忽略手势密码
				com.yylending.las.Global.setThirdPartyPageOpenedFlag(true);
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getPackageName()));
				startActivity(intent);
				dialog.dismiss();
			}
		}, true);
	}

	/**
	 * 网络返回时不dismiss dialog，父类实现默认dismiss
	 */
	@Override
	public void onFunctionalCompleted(boolean autoTips) {
	}

	private void changeViewStatus(int status) {
		CLog.i(TAG, "改提示信息：changeViewStatus");

		switch (status) {
			case STATUS_CONNECTION:
				mConnectionState.setImageResource(R.drawable.ic_apply_connection);
				updateQueuePositionInfo();
				mWaitingTime.setText("");
				mActionBtn.setVisibility(View.INVISIBLE);
				mActionBtn.setText(R.string.apply_connect);
				connect();
				break;
			case STATUS_CANCEL:
				mConnectionState.setImageResource(R.drawable.ic_video_for_call);
				updateQueuePositionInfo();
				mActionBtn.setVisibility(View.VISIBLE);
				mActionBtn.setText(R.string.dequeue);
				break;
			case STATUS_RECONNECTION:
				mQueuePosition.setText("");
				mWaitingTime.setText("");
				mActionBtn.setVisibility(View.VISIBLE);
				mActionBtn.setText(R.string.apply_reconnection);
				break;
		}
	}

	private void connect(){
		//直接申请连线
		StatService.onEvent(this, StatIDSet.EVENT_ID_TO_APPLY_FOR_THE_ATTACHMENT);
		if (mGrantedCamera && mGrantedMicrophone) {
			showLoading(true);
			mAnyChatPresenter.incomingQueue();
		} else {
			applyPermission();
		}
	}

	private void updateQueuePositionInfo() {
		CLog.i(TAG, "mStatus = " + mStatus + ", mQueueLength = " + mQueueLength + ", mQueueCurrent = " + mQueueCurrent);

		if (mStatus == STATUS_CANCEL && mQueueCurrent == -1) {
			mQueuePosition.setText(getString(R.string.queue_people_you_are_ready));
			mWaitingTime.setText(getString(R.string.video_verify_need_wait, mCounter));
			return;
		}
		if (mQueueLength == -1) {
			mQueuePositionIcon.setVisibility(View.GONE);
			mQueuePosition.setText("");
		} else {
			CLog.i(TAG, "当前状态：" + (mStatus == STATUS_CANCEL ? "排队中" : "未排队") + ", 队列前面人数返回的是：" + mQueueCurrent);
			mQueuePositionIcon.setVisibility(View.VISIBLE);
			String current = String.format(getString(R.string.queue_people_before_you), mQueueCurrent + 1);
			mQueuePosition.setText(current);
		}
	}

	@Override
	public void onSignResult(SignModel.Sign result) {
		mNumber = result.taskNo;
		CLog.i(TAG, "签名结果：taskNo = " + mNumber);

		String appID = Global.ANY_CHAT_APP_ID;
		String sign = result.sign;
		long timestamp = Long.parseLong(result.timestamp);
		CLog.i(TAG, "appId = " + appID + ", sign = " + sign + ", timestamp = " + timestamp);
		mAnyChatPresenter.login(mNumber, mNumber, timestamp, sign);
	}

	@Override
	public void onSignFailed(String msg) {
		dismissLoading();
		showLongToast(msg);
	}

	@Override
	public void loginResult(int errorCode) {
		dismissLoading();
		CLog.i(TAG, "登录结果：loginResult = " + errorCode);
		if (errorCode != 0) {
//			AnyChat.EVENT_CONNECT_SERVER_FAILED//连接视频云失败
//			AnyChat.EVENT_CONNECT_BREAK_FAILED//视频云连接断开
//			AnyChat.EVENT_CONNECT_BUSINESS_HALL_FAILED//进入营业厅失败
//			AnyChat.EVENT_ENTER_ROOM_FAILED//进入房间失败
			dismissLoading();
			showToast(R.string.incoming_queue_failed);
			finish();
		} else {
			mActionBtn.setEnabled(true);
		}
	}

	@Deprecated
	@Override
	public void enterRoomResult(int roomId) {
//		RemoteVideoActivity.start(this, mCallingUserId, roomId);
	}

	private int mQueueLength = -1;
	private int mQueueCurrent = -1;

	@Override
	public void roomUserNum(int num, int front) {
		CLog.i(TAG, "房间用户信息：roomUserNum num="+num+";front="+front);
		dismissLoading();
		//忽略重复回调
		if(mQueueLength == num && mQueueCurrent == front){
			return;
		}

		int originalQueueLength = mQueueLength;
		int originalQueueCurrent = mQueueCurrent;

		mQueueLength = num;
		mQueueCurrent = front;

		changeViewStatus(mStatus);

		if (front != -1) {//成功排队，开始计时
			mStatus = STATUS_CANCEL;
			changeViewStatus(STATUS_CANCEL);

			if (mTimerTask != null) {
				mTimerTask.cancel();
				mTimerTask = null;
			}
			if (mTimer != null) {
				mTimer.cancel();
				mTimer = null;
			}
			mTimerTask = new TimerTask() {
				@Override
				public void run() {
					mTimeHandler.sendEmptyMessage(TIME_UPDATE);
				}
			};

			mTimer = new Timer();
			mTimer.schedule(mTimerTask, 0, 60000);
			if(originalQueueCurrent != mQueueCurrent){
				mCounter = 6;
			}
			//String time = getString(R.string.video_verify_need_wait, (mQueueCurrent + 1) * 6);
			//mWaitingTime.setText(time);
		}
	}

	private int mCallingUserId = -1;
	private String mCallingUserName = "";

	@Override
	public void remoteVideoCalling(final int userId) {
		CLog.i(TAG, "收到呼叫：remoteVideoCalling()");
		mCallingUserId = userId;
		mAnyChatPresenter.mCallingUserId = userId;
		mCallingUserName = mAnyChatPresenter.getUserName(userId);

		if (isFinishing())
			return;//isDestroyed() api 17
		AnyChat.playCallingSession(this);
		VideoAcceptActivity.start(this);
	}

	@Override
	public void remoteVideoStarting(int userId, int roomId) {
		CLog.i(TAG, "开始视频：remoteVideoStarting()");
		mCallingUserId = userId;
//		mRoomId = roomId;
		AnyChat.stopCallingSession(this);
		RemoteVideoActivity.start(this, userId, roomId);
	}

	@Override
	public void callingCanceled() {
		CLog.i(TAG, "呼叫关闭：callingCanceled()");
		AnyChat.stopCallingSession(this);
		mAnyChatPresenter.releaseAnyChat();
		Toast.makeText(this, "视频呼叫已取消，请重试", Toast.LENGTH_LONG).show();
		EventAgent.post(new VideoAcceptActivity.CloseVideoWaitEvent());
		finish();//取消视频后需要重新进入，以获取签名
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RemoteVideoActivity.REQUEST_CODE) {
			CLog.i(TAG, "视频结束：onActivityResult()");
			mStatus = STATUS_RECONNECTION;
			mAnyChatPresenter.releaseAnyChat();
			mMyQuotaPresenter.myQuota();
		} else if (requestCode == VideoAcceptActivity.REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				StatService.onEvent(VideoVerifyActivity.this, StatIDSet.EVENT_ID_ANSWER_THE_PHONE);
				mAnyChatPresenter.handleCalling(mCallingUserId, AnyChatDefine.BRAC_ERRORCODE_SUCCESS);
				AnyChat.stopCallingSession(VideoVerifyActivity.this);
			} else {
				mStatus = STATUS_CONNECTION;
				StatService.onEvent(VideoVerifyActivity.this, StatIDSet.EVENT_ID_REFUSED_TO_CALL);
				mAnyChatPresenter.handleCalling(mCallingUserId, AnyChatDefine.BRAC_ERRORCODE_SESSION_REFUSE);
				mAnyChatPresenter.quitQueue();
				AnyChat.stopCallingSession(VideoVerifyActivity.this);
				mAnyChatPresenter.releaseAnyChat();
				finish();//取消视频后需要重新进入，以获取签名
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void videoVerifySuccess() {
		dismissLoading();
		mConnectionContainer.setVisibility(View.GONE);
		mVerifyCompleteContainer.setVisibility(View.VISIBLE);
		mLoanMoney.setText(String.format(getString(R.string.loan_money_quota), FormatUtils.getDecoratedAmount(mLoanAmount)));
		View complete = findViewById(R.id.video_verify_complete_btn);
		complete.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				StatService.onEvent(VideoVerifyActivity.this, StatIDSet.EVENT_ID_COMPLETE_VIDEO_AUTHENTICATION);
				finish();
			}
		});
	}

	@Override
	public void showLoanPage(int page, MyQuotaModel.ApplyStatus result) {
		//判断用户额度状态
		if (Constants.PAGE_NO_LOAN_STATUS_RESEARCH == page && result.loanState == Constants.LOAN_STATUS_ING) {
			videoVerifySuccess();
		} else {
			finish();
		}
	}

	@Override
	public void getStatusFail(String msg) {
		finish();
	}

	@Override
	public void creditReportingOutdated() {
		finish();
	}
}
